<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of "myWiWall".
# Copyright (c) 2008 JanRain, CRP Henri Tudor and contributors.
# All rights reserved.
#
# This file is dual-licenced under GPL v2.0 and Apache v2.0 licences
#
# ***** END LICENSE BLOCK *****
class Openid {
   
    // called before the openid server
	public function try_auth($openid) {


	    	$url	= HttpRequest::getPathUrl();
	    	$nb		= strlen($url);
	    	$base_url = '';
		if ($nb == 0 || $url[$nb-1] != "/") {
	    		$base_url = "http://".$_SERVER['HTTP_HOST'].$url. "/";
	    	} else {
	    		$base_url = "http://".$_SERVER['HTTP_HOST'].$url;
	    	}
	    	    		    
	    $trust_root = $base_url;
	    $return_url = $base_url.'index.php/openid/finish_auth';
	
        $store = new WMySqlStore(DbUtil::accessFactory());
        $store->createTables();	
	
	    $consumer =& new Auth_OpenID_Consumer($store);

	    // Begin the OpenID authentication process.
	    $auth_request = $consumer->begin($openid);
	

	
	    // No auth request means we can't begin OpenID.
	    if (!$auth_request) {   	
			$_SESSION['isError'] = true;
			$_SESSION['message'] = __("Authentication error; not a valid OpenID.");
			DefaultFC::redirection('users/index');
			exit;	        
	    } 
	    
	    // Redirect the user to the OpenID server for authentication.
	    // Store the token for this authentication so we can verify the
	    // response.
	
	    // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
	    // form to send a POST request to the server.
	    if ($auth_request->shouldSendRedirect()) {
	        $redirect_url = $auth_request->redirectURL($trust_root,
	                                                   $return_url);
	        // If the redirect URL can't be built, display an error
	        // message.
	        if (Auth_OpenID::isFailure($redirect_url)) {
				$_SESSION['isError'] = true;
				$_SESSION['message'] = __("Could not redirect to server: ") . $redirect_url->message;
				DefaultFC::redirection('users/index');
				exit;			            
	        } else {
	            // Send redirect.
	            header("Location: ".$redirect_url);
	        }
	    } else {
	        // Generate form markup and render it.
	        $form_id = 'openid_message';
	        $form_html = $auth_request->htmlMarkup($trust_root, $return_url,
	                                               false, array('id' => $form_id));
	
	        // Display an error if the form markup couldn't be generated;
	        // otherwise, render the HTML.
	        if (Auth_OpenID::isFailure($form_html)) {
				$_SESSION['isError'] = true;
				$_SESSION['message'] = __("Could not redirect to server: ") . $form_html->message;
				DefaultFC::redirection('users/index');
				exit;		            
	        } else {
	            print $form_html;
	        }
	    }
	}    

	// called after the openid server
	public function finish_auth() {
		
		$always_trust = false;
		if (isset($_GET['pal_trust'])) {
			$always_trust = true;
			// we hide this parameter from the openid library
			unset($_GET['pal_trust']);
	 		$_SERVER['QUERY_STRING'] = str_replace('&pal_trust=true', '', $_SERVER['QUERY_STRING']);			
		}

		$db = DbUtil::accessFactory();
        $store = new WMySqlStore($db);
        $store->createTables();	
		
	    $consumer =& new Auth_OpenID_Consumer($store);


	    	$url	= HttpRequest::getPathUrl();
	    	$nb		= strlen($url);
	    	$base_url = '';
		if ($nb == 0 || $url[$nb-1] != "/") {
	    		$base_url = "http://".$_SERVER['HTTP_HOST'].$url. "/";
	    	} else {
	    		$base_url = "http://".$_SERVER['HTTP_HOST'].$url;
	    	}
	    	    		    
	    $return_url = $base_url.'index.php/openid/finish_auth';	

	    // Complete the authentication process using the server's
	    // response.

	    $response = $consumer->complete($return_url);
		$success = false;
	
	    // Check the response status.
	    if ($response->status == Auth_OpenID_CANCEL) {
	        // This means the authentication was cancelled.
	        $msg = __('Verification cancelled.');
	    } else if ($response->status == Auth_OpenID_FAILURE) {
	        // Authentication failed; display the error message.
	        $msg = __("OpenID authentication failed: ") . $response->message;
	    } else if ($response->status == Auth_OpenID_SUCCESS) {
	    	$success = true;
	    	
	        // This means the authentication succeeded; extract the
	        // identity URL and Simple Registration data (if it was
	        // returned).
	        $openid = $response->getDisplayIdentifier();

	
			Auth::loginByOpenid($openid);
	
			if (!Auth::isAuth()) {
				$success = false;
				$msg = __('Account not found.');
			}
	    }

		if($success)
		{
			// for openid sso
			if (OPENID_SSO_MODE) {
		        if ($always_trust) {
		        	setcookie('default_openid', $openid, time()+60*60*24*30*12, HttpRequest::getPathUrl());
		        }
			}

			// Authentication process succeeded.
			// FIXME: log this connection

			
			// Redirection in the portal.
			DefaultFC::redirection('wall/index');
			exit;
		}
		else
		{
			$_SESSION['isError'] = true;
			$_SESSION['message'] = $msg;
			
			DefaultFC::redirection('users/index');
			exit;
		}
	}
}
?>